/**
 *  正则
 */

#import "NSString+Extension.h"

@implementation NSString (Extension)

/**
 * 检查是否是手机号
 */
- (BOOL)isPhoneNumber {
    
    // 1开头 后10个数字
    NSString *phoneRegex = @"^1[\\d]{10}$";
    
    NSPredicate *phoneTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",phoneRegex];
    
    return [phoneTest evaluateWithObject:self];
    
    return YES;
}

#pragma mark - 是否是数字

- (BOOL)isNumber {
    
    //手机号以13， 15，18开头，八个 \d 数字字符
    //    NSString *phoneRegex = @"^((13[0-9])|(15[^4,\\D])|(18[0,0-9]))\\d{8}$";
    
    // 1开头 后10个数字
    NSString *phoneRegex = @"[\\d]*";
    
    NSPredicate *phoneTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",phoneRegex];
    
    return [phoneTest evaluateWithObject:self];
    
    return YES;
}


#pragma mark - 获得字符串的字符数
/**
 *  下面2个方法效果一致，先保留
 */
/**
 *  得到当前字符串的字符数,1个汉字2个字符
 */
- (int)charCount
{
    int strlength = 0;
    char* p = (char*)[self cStringUsingEncoding:NSUnicodeStringEncoding];
    for (int i=0 ; i<[self lengthOfBytesUsingEncoding:NSUnicodeStringEncoding] ;i++) {
        if (*p) {
            p++;
            strlength++;
        }
        else {
            p++;
        }
        
    }
    return strlength;
}
/**
 *  得到当前字符串的字符数,1个汉字2个字符
 *  暂时不要用这个方法, 统一使用 - (int)charCount
 */
- (NSInteger)charCount1
{
    NSStringEncoding enc = CFStringConvertEncodingToNSStringEncoding(kCFStringEncodingGB_18030_2000);
    NSData* da = [self dataUsingEncoding:enc];
    return [da length];
}

/**
 *  将GBK编码的二进制数据转换成字符串
 */
+ (NSString *)UTF8StringWithHZGB2312Data:(NSData *)data
{
    NSStringEncoding encoding = CFStringConvertEncodingToNSStringEncoding(kCFStringEncodingGB_18030_2000);
    return [[NSString alloc] initWithData:data encoding:encoding];
}

/**
 *  查找并返回第一个匹配的文本内容
 */
- (NSString *)firstMatchWithPattern:(NSString *)pattern
{
    NSError *error = nil;
    NSRegularExpression *regex = [NSRegularExpression
                                  regularExpressionWithPattern:pattern
                                  options:NSRegularExpressionCaseInsensitive | NSRegularExpressionDotMatchesLineSeparators
                                  error:&error];
    
    if (error) {
        NSLog(@"匹配方案错误:%@", error.localizedDescription);
        return nil;
    }
    
    NSTextCheckingResult *result = [regex firstMatchInString:self options:0 range:NSMakeRange(0, self.length)];
    
    if (result) {
        NSRange r = [result rangeAtIndex:1];
        return [self substringWithRange:r];
    } else {
        NSLog(@"没有找到匹配内容 %@", pattern);
        return nil;
    }
}

/**
 *  查找多个匹配方案结果
 */
- (NSArray *)matchesWithPattern:(NSString *)pattern
{
    NSError *error = nil;
    NSRegularExpression *regex = [NSRegularExpression
                                  regularExpressionWithPattern:pattern
                                  options:NSRegularExpressionCaseInsensitive | NSRegularExpressionDotMatchesLineSeparators
                                  error:&error];
    
    if (error) {
        NSLog(@"匹配方案错误:%@", error.localizedDescription);
        return nil;
    }
    
    return [regex matchesInString:self options:0 range:NSMakeRange(0, self.length)];
}


/**
 *  编码后的urlString
 */
- (NSString *)StringByURLEncoding {
    NSString *path = [self stringByDeletingLastPathComponent];
    NSString *resourceName = [self lastPathComponent];
    return [path stringByAppendingPathComponent:[resourceName URLEncodedString]];
}

/**
 *  解码后的urlString
 */
- (NSString *)StringByURLDecoding {
    NSString *path = [self stringByDeletingLastPathComponent];
    NSString *resourceName = [self lastPathComponent];
    return [path stringByAppendingPathComponent:[resourceName URLDecodedString]];
}
/**
 *  编码
 */
- (NSString *)URLEncodedString {
    NSString *result = (NSString *)
    CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault,
                                                              (CFStringRef)self,
                                                              NULL,
                                                              CFSTR("!*'();:@&=+$,/?%#[] "),
                                                              kCFStringEncodingUTF8));
    return result;
}
/**
 *  解码
 */
- (NSString*)URLDecodedString
{
    NSString *result = (NSString *)
    CFBridgingRelease(CFURLCreateStringByReplacingPercentEscapesUsingEncoding(kCFAllocatorDefault,
                                                                              (CFStringRef)self,
                                                                              CFSTR(""),
                                                                              kCFStringEncodingUTF8));
    return result;
}

/**
 *  查找多个匹配方案结果，并根据键值数组生成对应的字典数组
 */
- (NSArray *)matchesWithPattern:(NSString *)pattern keys:(NSArray *)keys
{
    NSArray *array = [self matchesWithPattern:pattern];
    
    if (array.count == 0) return nil;
    
    NSMutableArray *arrayM = [NSMutableArray array];
    for (NSTextCheckingResult *result in array) {
        NSMutableDictionary *dictM = [NSMutableDictionary dictionary];
        
        for (int i = 0; i < keys.count; i++) {
            NSRange r = [result rangeAtIndex:(i + 1)];
            
            [dictM setObject:[self substringWithRange:r] forKey:keys[i]];
        }
        [arrayM addObject:dictM];
    }
    return [arrayM copy];
}

- (NSInteger)getStringLengthWithString
{
    __block NSInteger stringLength = 0;
    [self enumerateSubstringsInRange:NSMakeRange(0, [self length])
                               options:NSStringEnumerationByComposedCharacterSequences
                            usingBlock:^(NSString *substring, NSRange substringRange, NSRange enclosingRange, BOOL *stop)
     {
         const unichar hs = [substring characterAtIndex:0];
         if (0xd800 <= hs && hs <= 0xdbff)
         {
             if (substring.length > 1)
             {
                 const unichar ls = [substring characterAtIndex:1];
                 const int uc = ((hs - 0xd800) * 0x400) + (ls - 0xdc00) + 0x10;
                 if (0x1d <= uc && uc <= 0x1f77f)
                 {
                     stringLength += 1;
                 }
                 else
                 {
                     stringLength += 1;
                 }
             }
             else
             {
                 stringLength += 1;
             }
         } else if (substring.length > 1)
         {
             const unichar ls = [substring characterAtIndex:1];
             if (ls == 0x20e3)
             {
                 stringLength += 1;
             }
             else
             {
                 stringLength += 1;
             }
         } else {
             if (0x2100 <= hs && hs <= 0x27ff)
             {
                 stringLength += 1;
             }
             else if (0x2B05 <= hs && hs <= 0x2b07)
             {
                 stringLength += 1;
             }
             else if (0x2934 <= hs && hs <= 0x2935)
             {
                 stringLength += 1;
             }
             else if (0x3297 <= hs && hs <= 0x3299)
             {
                 stringLength += 1;
             }
             else if (hs == 0xa9 || hs == 0xae || hs == 0x303d || hs == 0x3030 || hs == 0x2b55 || hs == 0x2b1c || hs == 0x2b1b || hs == 0x2b50)
             {
                 stringLength += 1;
             }
             else
             {
                 stringLength += 1;
             }
         }
     }];

    return stringLength;
}


#pragma mark - emoji 表情

- (BOOL)stringContainsEmoji
{
    __block BOOL returnValue = NO;
    
    [self enumerateSubstringsInRange:NSMakeRange(0, [self length])
                               options:NSStringEnumerationByComposedCharacterSequences
                            usingBlock:^(NSString *substring, NSRange substringRange, NSRange enclosingRange, BOOL *stop) {
                                const unichar hs = [substring characterAtIndex:0];
                                if (0xd800 <= hs && hs <= 0xdbff) {
                                    if (substring.length > 1) {
                                        const unichar ls = [substring characterAtIndex:1];
                                        const int uc = ((hs - 0xd800) * 0x400) + (ls - 0xdc00) + 0x10000;
                                        if (0x1d000 <= uc && uc <= 0x1f77f) {
                                            returnValue = YES;
                                        }
                                    }
                                } else if (substring.length > 1) {
                                    const unichar ls = [substring characterAtIndex:1];
                                    if (ls == 0x20e3) {
                                        returnValue = YES;
                                    }
                                } else {
                                    if (0x2100 <= hs && hs <= 0x27ff) {
                                        returnValue = YES;
                                    } else if (0x2B05 <= hs && hs <= 0x2b07) {
                                        returnValue = YES;
                                    } else if (0x2934 <= hs && hs <= 0x2935) {
                                        returnValue = YES;
                                    } else if (0x3297 <= hs && hs <= 0x3299) {
                                        returnValue = YES;
                                    } else if (hs == 0xa9 || hs == 0xae || hs == 0x303d || hs == 0x3030 || hs == 0x2b55 || hs == 0x2b1c || hs == 0x2b1b || hs == 0x2b50) {
                                        returnValue = YES;
                                    }
                                }
                            }];
    
    return returnValue;
}



#pragma mark - Substring

/**
 *  裁剪前缀
 */
- (NSString *)substringByTrimPrefix:(NSString *)preffix {
    if ([self hasPrefix:preffix]) {
        NSRange range = [self rangeOfString:preffix];
        return [self substringFromIndex:(range.location + range.length)];
    }
    return self;
}

/**
 *  裁剪后缀
 */
- (NSString *)substringByTrimSuffix:(NSString *)suffix {
    if ([self hasSuffix:suffix]) {
        NSRange range = [self rangeOfString:suffix options:NSBackwardsSearch];
        return [self substringToIndex:range.location];
    }
    return self;
}

/**
 *  前后同时裁减掉一个字符串
 */
- (NSString *)substringByTrim:(NSString *)trimString {
    NSString *tempStrin = [self substringByTrimPrefix:trimString];
    return [tempStrin substringByTrimSuffix:trimString];
}

#pragma mark 裁剪空格
///**
// *  裁剪前面所有的空格
// */
//- (NSString *)substringByTrimPrefixSpacing {
//
//
//
//    return self ;
//}
//
///**
// *  裁剪后面所有的空格
// */
//- (NSString *)substringByTrimSuffixSpacing {
//    return self;
//}
//
/**
 *  裁剪前后所有的空格
 */
- (NSString *)substringByTrimSpacing {
    return [self stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
}


@end
